package jsu.hx.lost.Controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import jsu.hx.lost.Model.entity.Notifications;
import jsu.hx.lost.Model.vo.ResponseResult;
import jsu.hx.lost.Service.NotificationsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/notifications")
public class NotificationsController {

    @Autowired
    private NotificationsService notificationsService;

    /**
     * 分页获取用户通知
     * @param pageNum 页码（默认1）
     * @param pageSize 每页数量（默认10）
     */
    @GetMapping("")
    public ResponseResult<IPage<Notifications>> getUserNotifications(
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize
    ) {
        // 从安全上下文中获取当前用户ID
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        Long userId = (Long) authentication.getPrincipal();

        IPage<Notifications> page = notificationsService.getNotificationsByUser(userId, pageNum, pageSize);
        return ResponseResult.success(page);
    }

    /**
     * 标记通知为已读
     * @param notificationId 通知ID
     */
    @PutMapping("/{notificationId}/read")
    public ResponseResult<Void> markNotificationAsRead(
            @PathVariable Long notificationId
    ) {
        boolean success = notificationsService.markAsRead(notificationId);
        return success ? ResponseResult.success() : ResponseResult.error("标记失败");
    }

    /**
     * 根据关联物品查询通知
     * @param relatedType 关联类型（LOST/FOUND）
     * @param itemId 物品ID
     */
    @GetMapping("/by-item")
    public ResponseResult<Notifications> getNotificationByRelatedItem(
            @RequestParam Long userId,
            @RequestParam String relatedType,
            @RequestParam Long itemId
    ) {
        Notifications notification = notificationsService.getByRelatedItem(userId,relatedType, itemId);
        return notification != null ?
                ResponseResult.success(notification) :
                ResponseResult.error("未找到相关通知");
    }
}